package com.anuyun.ms.base.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.anuyun.ms.base.config.property.FeatureProperty;
import com.anuyun.ms.base.context.UserContext;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;

import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

@Configuration
public class MybatisPlusConfig {
	
	@Autowired
	FeatureProperty featureProperty;

	@Bean
	public MybatisPlusInterceptor mybatisPlusInterceptor() {
		MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
		if(FeatureProperty.TENANT_MODE) {
			interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
				@Override
				public Expression getTenantId() {
					if(StringUtils.isNotBlank(UserContext.getTenantId())) {
						return new StringValue(UserContext.getTenantId());
					}else {
						return new StringValue("1");
					}
				}
				
				// 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
				@Override
				public boolean ignoreTable(String tableName) {
					return "tenant".equalsIgnoreCase(tableName);
				}
				
				@Override
				public String getTenantIdColumn() {
					return "tenant_id";
				}
			}));
		}
		// 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
		// 如果用了分页插件注意先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor
		// 用了分页插件必须设置 MybatisConfiguration#useDeprecatedExecutor = false
		// 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
		return interceptor;
	}

}
